package com.java.zhuiyun.api.uploader.controller;

import com.java.zhuiyun.api.dto.FileChunkDTO;
import com.java.zhuiyun.api.dto.FileChunkResultDTO;
import com.java.zhuiyun.api.uploader.service.UploadService;
import com.java.zhuiyun.api.file_manager.entity.RestApiResponse;
import com.java.zhuiyun.common.response.CommonResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @ClassName UploaderController
 * @Description TODO
 * @Author MJL
 * @Date 2023/8/16 13:38
 **/
@RestController
@RequestMapping("/upload")
public class UploadController {
    @Resource
    private UploadService uploadService;

    /**
    * @Author MJL
    * @Description todo 检查分片是否存在
    * @Date 2023/8/16 13:47
    * @Return  * @param null
    */
    @GetMapping("/chunk")
    public RestApiResponse<Object> checkChunkExist(FileChunkDTO chunkDTO) {
        FileChunkResultDTO fileChunkResultDTO;
        try {
            fileChunkResultDTO = uploadService.checkChunkExist(chunkDTO);
            return RestApiResponse.success(fileChunkResultDTO);
        } catch (Exception e) {
            return RestApiResponse.error(e.getMessage());
        }
    }
    /**
    * @Author MJL
    * @Description todo 上传分片文件
    * @Date 2023/8/16 14:18
    * @Return  * @param null
    */
    @PostMapping("/chunk")
    public RestApiResponse<Object> uploadChunk(FileChunkDTO chunkDTO) {
        try {
            uploadService.uploadChunk(chunkDTO);
            return RestApiResponse.success(chunkDTO.getIdentifier());
        } catch (Exception e) {
            return RestApiResponse.error(e.getMessage());
        }
    }
    /**
    * @Author MJL
    * @Description todo 请求合并分片文件
    * @Date 2023/8/16 14:27
    * @Return  * @param null
    */
    @PostMapping("/merge")
    public CommonResult mergeChunks(@RequestBody FileChunkDTO chunkDTO) {
        try {

            return CommonResult.ok(uploadService.mergeChunk(chunkDTO.getIdentifier(), chunkDTO.getFilename(), chunkDTO.getTotalChunks(), chunkDTO.getUploadedBy()));
        } catch (Exception e) {
            return CommonResult.error(RestApiResponse.error(e.getMessage()));
        }
    }
}
